const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const config = require('./config/index')
const utils = require('./public/utils');
const mongoose = require('mongoose');
//数据库地址
const dbUrl = config.dataBase.host + ':' + config.dataBase.port + '/' + config.dataBase.dbRepertory;
mongoose.connect('mongodb://' + dbUrl,{ useNewUrlParser: true })    //链接数据库
    .then(() => {
        console.log('数据库连接成功!')
    })
    .catch((err) => {
        console.log('数据库连接失败!')
        throw err
    })


const app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


//定期清理垃圾文件
// utils.setTimeClearFile(config.source.imgUploadPath);

app.use(cookieParser());

//处理接口跨域
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);  //不能使用 "*" ，因为要跨域对浏览器进行cookie的操作，使用"*"跨域操作浏览器cookie，浏览器会进行拦截。
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,token");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Access-Control-Allow-Credentials",true);  //允许跨域接收浏览器的cookie
    res.header("Access-Control-Max-Age",3628800);
    next();
});

const router = require('./router/')(app);

// error handler
app.use('*',function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  next();
});

/**
 * 404错误处理
 * catch 404 and forward to error handler
 * js文件写空
 */
app.use("*",function(req, res, next) {
    if(path.extname(path.basename(req._parsedUrl.pathname)) === ".js"){
        res.send("")
        res.end()
    }else{
        let err = new Error('Not Found');
        err.status = 404;
        res.send('404');
    }
});

module.exports = app;
